<template>
  <el-card class="u9-api-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-icon><DataBoard /></el-icon>
        <span class="header-title">库存查询系统</span>
      </div>
    </template>

    <!-- 统一的查询参数配置区 -->
    <div class="business-config">
      <h4>查询参数</h4>
      <el-form :model="businessParams" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码">
              <el-input 
                v-model="businessParams.itemCode" 
                placeholder="输入物料编码，支持多个（用逗号分隔）"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次编码">
              <el-input 
                v-model="businessParams.lotCode" 
                placeholder="可选：输入批次编码，留空查询所有批次"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 统一的功能按钮区 -->
    <div class="action-section">
      <el-row :gutter="20" justify="center">
        <el-col :span="6">
          <el-button 
            type="primary" 
            size="large"
            @click="queryAllSystems"
            :loading="loadingStock || loadingSmis"
            :icon="Position"
            style="width: 100%; font-weight: 600;"
          >
            查询库存
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            accept=".xlsx,.xls"
            :on-change="handleExcelImport"
            style="width: 100%;"
          >
            <el-button 
              type="warning" 
              size="large"
              :icon="Upload"
              style="width: 100%; font-weight: 600;"
              :loading="batchLoading"
            >
              批量导入Excel
            </el-button>
          </el-upload>
        </el-col>
        <el-col :span="6">
          <el-button 
            type="info" 
            size="large"
            @click="downloadTemplate"
            :icon="Download"
            style="width: 100%; font-weight: 600;"
          >
            下载导入模板
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button 
            type="success" 
            size="large"
            @click="exportCombinedToExcel"
            :icon="Download"
            style="width: 100%; font-weight: 600;"
            :disabled="(!responseStock?.success || u9MaterialTableData.length === 0) && (!responseSmis?.success || smisMaterialTableData.length === 0)"
          >
            导出库存Excel
          </el-button>
        </el-col>
      </el-row>
      
      <div class="help-text">
        <el-text type="info" size="small">
          提示：留空批次编码可查询该物料的所有批次信息。支持Excel批量导入查询，导入格式：物料编码、批次编码。
        </el-text>
      </div>
    </div>

    <!-- 合并结果查询区 -->
    <div v-if="(responseStock?.success || responseSmis?.success) && combinedMaterialTableData.length > 0" class="response-section">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <h4 style="margin: 0;">
          库存查询结果
        </h4>
        <!-- 零库存开关 -->
        <div style="display: flex; align-items: center; gap: 16px;">
          <el-switch
            v-if="responseStock?.success"
            v-model="showZeroStockU9"
            active-text="显示U9零库存"
            inactive-text="隐藏U9零库存"
          />
          <el-switch
            v-if="responseSmis?.success"
            v-model="showZeroStockSmis"
            active-text="显示配料岛零库存"
            inactive-text="隐藏配料岛零库存"
          />
        </div>
      </div>
      
      <!-- 查询状态提示 -->
      <div style="display: flex; gap: 8px; margin-bottom: 16px;">
        <el-alert 
          v-if="responseStock?.success"
          title="U9系统查询成功" 
          type="success"
          :closable="false"
          size="small"
        />
        <el-alert 
          v-else-if="responseStock && !responseStock.success"
          title="U9系统查询失败" 
          type="error"
          :closable="false"
          size="small"
        />
        
        <el-alert 
          v-if="responseSmis?.success"
          title="配料岛系统查询成功" 
          type="success"
          :closable="false"
          size="small"
        />
        <el-alert 
          v-else-if="responseSmis && !responseSmis.success"
          title="配料岛系统查询失败" 
          type="error"
          :closable="false"
          size="small"
        />
      </div>
      
      <el-tabs type="border-card">
        <el-tab-pane label="合并库存（表格）">
          <div class="table-summary">
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <el-text type="info">
                共查询到 {{ combinedTableStats.totalRecords }} 条记录，
                {{ combinedTableStats.uniqueMaterials }} 种物料，
                {{ combinedTableStats.uniqueLots }} 个批次
                （U9：{{ combinedTableStats.u9Records }}条，配料岛：{{ combinedTableStats.smisRecords }}条）
              </el-text>
            </div>
          </div>

          <el-table 
            :data="combinedMaterialTableData" 
            :span-method="combinedArraySpanMethod"
            border 
            stripe
            style="width: 100%; margin-top: 16px;"
            height="500"
            class="combined-table"
            :row-class-name="({ row }) => `system-row-${row.systemType.toLowerCase()}`"
          >
            <el-table-column prop="ItemCode" label="物料编码" width="180" show-overflow-tooltip class-name="material-info-cell" />
            <el-table-column prop="ItemName" label="物料名称" width="150" show-overflow-tooltip class-name="material-info-cell" />
            <el-table-column prop="ItemSpec" label="型号" width="200" show-overflow-tooltip class-name="material-info-cell" />
            <el-table-column prop="LotCode" label="批次号" width="200" show-overflow-tooltip class-name="lot-code-cell" />
            <el-table-column prop="systemType" label="系统" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.systemColor" size="small">
                  {{ scope.row.systemTag }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="WhName" label="仓库名称" width="150" show-overflow-tooltip />
            <el-table-column prop="StoreQty" label="库存量" width="120" align="right">
              <template #default="scope">
                <el-tag :type="scope.row.StoreQty > 0 ? 'success' : 'danger'">
                  {{ scope.row.StoreQty }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="OrgName" label="组织名称" width="200" show-overflow-tooltip />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 无数据提示 -->
    <div v-else-if="responseStock || responseSmis" class="response-section">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <h4 style="margin: 0;">
          查询结果
        </h4>
      </div>
      
      <!-- 查询状态提示 -->
      <div style="display: flex; gap: 8px; margin-bottom: 16px;">
        <el-alert 
          v-if="responseStock?.success"
          title="U9系统查询成功，但无数据" 
          type="warning"
          :closable="false"
          size="small"
        />
        <el-alert 
          v-else-if="responseStock && !responseStock.success"
          :title="`U9系统查询失败：${responseStock.error}`" 
          type="error"
          :closable="false"
          size="small"
        />
        
        <el-alert 
          v-if="responseSmis?.success"
          title="配料岛系统查询成功，但无数据" 
          type="warning"
          :closable="false"
          size="small"
        />
        <el-alert 
          v-else-if="responseSmis && !responseSmis.success"
          :title="`配料岛系统查询失败：${responseSmis.error}`" 
          type="error"
          :closable="false"
          size="small"
        />
      </div>
      
      <el-empty description="暂无查询结果" />
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataBoard, Position, Upload, Download, Refresh } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import DataService from '../services/dataService.js'
import { useDataStore } from '../stores/dataStore.js'

const dataStore = useDataStore()

// 统一的查询参数
const businessParams = reactive({
  itemCode: 'PT0302-220674', // 默认物料编码（可修改为实际需要查询的物料）
  lotCode: '' // 批次编码默认为空，留空时查询该物料的所有批次
})

// 状态管理
const loadingStock = ref(false)
const loadingSmis = ref(false)
const batchLoading = ref(false)
const responseStock = ref(null)
const responseSmis = ref(null)
const responseTimeStock = ref(0)
const responseTimeSmis = ref(0)
const showZeroStockU9 = ref(true) // 是否显示U9零库存记录
const showZeroStockSmis = ref(true) // 是否显示SMIS零库存记录
const uploadRef = ref()
const batchResults = ref([]) // 批量查询结果

/**
 * 解析响应数据为表格数据的通用函数
 * @param {Object} responseData - 响应数据
 * @returns {Array} 解析后的数组数据
 */
const parseResponseData = (responseData) => {
  if (!responseData) return []

  let dataArray = []

  try {
    // 检查Data字段是否为字符串（需要解析）还是已经是对象
    if (responseData.Data && typeof responseData.Data === 'string') {
      dataArray = JSON.parse(responseData.Data)
    } else if (responseData.Data && Array.isArray(responseData.Data)) {
      dataArray = responseData.Data
    } else if (Array.isArray(responseData)) {
      dataArray = responseData
    } else if (responseData.d && responseData.d.Data) {
      if (typeof responseData.d.Data === 'string') {
        dataArray = JSON.parse(responseData.d.Data)
      } else {
        dataArray = responseData.d.Data
      }
    }

    // 确保 dataArray 是数组
    if (!Array.isArray(dataArray)) {
      return []
    }

    return dataArray
  } catch (error) {
    return []
  }
}

/**
 * U9物料库存表格数据计算属性
 */
const u9MaterialTableData = computed(() => {
  if (!responseStock.value?.success || !responseStock.value?.data) {
    return []
  }
  
  try {
    const dataArray = parseResponseData(responseStock.value.data)
    
    if (dataArray.length === 0) return []

    // 转换为表格数据格式
    const tableData = dataArray.map((item, index) => {
      return {
        id: index + 1,
        ItemCode: item.ItemCode || '-',
        ItemName: item.ItemName || '-', 
        ItemSpec: item.ItemSpec || '-',
        LotCode: item.LotCode || '-',
        WhName: item.WhName || '-',
        StoreQty: Number(item.StoreQty) || 0,
        LendQty: Number(item.LendQty) || 0,
        OrgName: item.OrgName || '-',
        OrgCode: item.OrgCode || '-',
        WhCode: item.WhCode || '-',
        _dataSource: 'u9'
      }
    })

    const processedData = processTableData(tableData)
    
    // 根据零库存开关过滤数据
    return showZeroStockU9.value ? processedData : processedData.filter(item => item.StoreQty > 0)
  } catch (error) {
    console.error('U9数据解析错误:', error)
    return []
  }
})

/**
 * SMIS配料岛库存表格数据计算属性
 */
const smisMaterialTableData = computed(() => {
  if (!responseSmis.value?.success || !responseSmis.value?.data) {
    return []
  }
  
  try {
    let dataArray = []
    
    // SMIS配料岛数据处理
    if (responseSmis.value.data.Data) {
      // 如果数据在Data字段中（JSON字符串格式）
      dataArray = JSON.parse(responseSmis.value.data.Data)
    } else if (Array.isArray(responseSmis.value.data)) {
      // 如果数据直接是数组格式
      dataArray = responseSmis.value.data
    } else if (responseSmis.value.data.data && Array.isArray(responseSmis.value.data.data)) {
      // 如果数据在data字段中
      dataArray = responseSmis.value.data.data
    }
    
    // 转换为表格数据格式
    const tableData = dataArray.map((item, index) => {
      return {
        id: index + 1,
        ItemCode: item.materialcode || '-',
        ItemName: item.materialname || '-', 
        ItemSpec: item.materialgg || '-',
        LotCode: item.venderlot || '-',
        WhName: item.warehousename || '-',
        StoreQty: Number(item.total) || 0,
        LendQty: Number(item.usestock) || 0,
        OrgName: '银河航天科技（南通）有限公司',
        OrgCode: 'YHHT_NT',
        WhCode: item.warehousecode || '-',
        _dataSource: 'smis'
      }
    })

    const processedData = processTableData(tableData)
    
    // 根据零库存开关过滤数据
    return showZeroStockSmis.value ? processedData : processedData.filter(item => item.StoreQty > 0)
  } catch (error) {
    console.error('SMIS数据解析错误:', error)
    return []
  }
})

/**
 * 处理表格数据的通用方法
 */
const processTableData = (tableData) => {
  // 按物料编码、物料名称、型号、批次号排序，确保相同物料和批次聚集在一起
  const sortedTableData = tableData.sort((a, b) => {
    const keyA = `${a.ItemCode}-${a.ItemName}-${a.ItemSpec}`
    const keyB = `${b.ItemCode}-${b.ItemName}-${b.ItemSpec}`
    
    if (keyA !== keyB) {
      // 不同物料按物料信息排序
      return keyA.localeCompare(keyB)
    }
    
    // 相同物料按批次号排序
    if (a.LotCode !== b.LotCode) {
      return a.LotCode.localeCompare(b.LotCode)
    }
    
    // 相同物料和批次按仓库名称排序
    return a.WhName.localeCompare(b.WhName)
  })

  return sortedTableData
}

/**
 * 计算表格合并信息
 * 对相同的物料编码、物料名称、型号进行合并处理
 * 对相同物料下的相同批次号也进行合并处理
 */
const spanData = computed(() => {
  const data = materialTableData.value
  if (!data || data.length === 0) return {}

  const spanInfo = {}

  // 按物料编码、物料名称、型号分组
  const materialGroups = []
  let currentMaterialGroup = null

  data.forEach((item, i) => {
    const materialKey = `${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`
    
    if (!currentMaterialGroup || currentMaterialGroup.key !== materialKey) {
      // 新的物料分组
      currentMaterialGroup = {
        key: materialKey,
        startIndex: i,
        count: 1,
        items: [item]
      }
      materialGroups.push(currentMaterialGroup)
    } else {
      // 同一物料分组
      currentMaterialGroup.count++
      currentMaterialGroup.items.push(item)
    }
  })

  // 计算物料合并信息
  materialGroups.forEach(materialGroup => {
    for (let i = 0; i < materialGroup.count; i++) {
      const rowIndex = materialGroup.startIndex + i
      
      if (i === 0) {
        // 第一行：显示合并的物料信息
        spanInfo[`${rowIndex}-0`] = [materialGroup.count, 1] // 物料编码
        spanInfo[`${rowIndex}-1`] = [materialGroup.count, 1] // 物料名称
        spanInfo[`${rowIndex}-2`] = [materialGroup.count, 1] // 型号
      } else {
        // 后续行：隐藏物料信息
        spanInfo[`${rowIndex}-0`] = [0, 0] // 物料编码
        spanInfo[`${rowIndex}-1`] = [0, 0] // 物料名称
        spanInfo[`${rowIndex}-2`] = [0, 0] // 型号
      }
    }

    // 在每个物料分组内，计算批次号合并信息
    const lotGroups = []
    let currentLotGroup = null
    
    materialGroup.items.forEach((item, itemIndex) => {
      const globalIndex = materialGroup.startIndex + itemIndex
      
      if (!currentLotGroup || currentLotGroup.lotCode !== item.LotCode) {
        // 新的批次分组
        currentLotGroup = {
          lotCode: item.LotCode,
          startIndex: globalIndex,
          count: 1,
          items: [item]
        }
        lotGroups.push(currentLotGroup)
      } else {
        // 同一批次分组
        currentLotGroup.count++
        currentLotGroup.items.push(item)
      }
    })

    // 计算批次号合并信息
    lotGroups.forEach(lotGroup => {
      for (let j = 0; j < lotGroup.count; j++) {
        const rowIndex = lotGroup.startIndex + j
        
        if (j === 0) {
          // 第一行：显示合并的批次号
          spanInfo[`${rowIndex}-3`] = [lotGroup.count, 1] // 批次号
        } else {
          // 后续行：隐藏批次号
          spanInfo[`${rowIndex}-3`] = [0, 0] // 批次号
        }
      }
    })
  })
  return spanInfo
})

/**
 * 计算唯一物料数量
 */
const uniqueMaterialCount = computed(() => {
  const data = materialTableData.value
  if (!data || data.length === 0) return 0
  
  const uniqueMaterials = new Set()
  data.forEach(item => {
    const materialKey = `${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`
    uniqueMaterials.add(materialKey)
  })
  
  return uniqueMaterials.size
})

/**
 * 计算唯一批次数量
 */
const uniqueLotCount = computed(() => {
  const data = materialTableData.value
  if (!data || data.length === 0) return 0
  
  const uniqueLots = new Set()
  data.forEach(item => {
    uniqueLots.add(item.LotCode)
  })
  
  return uniqueLots.size
})

/**
 * U9数据统计信息
 */
const u9OriginalDataStats = computed(() => {
  if (!responseStock.value?.success || !responseStock.value?.data) {
    return { total: 0, withStock: 0, zeroStock: 0 }
  }

  try {
    const dataArray = parseResponseData(responseStock.value.data)
    
    if (!Array.isArray(dataArray)) {
      return { total: 0, withStock: 0, zeroStock: 0 }
    }

    const total = dataArray.length
    const withStock = dataArray.filter(item => Number(item.StoreQty) > 0).length
    const zeroStock = total - withStock

    return { total, withStock, zeroStock }
  } catch (error) {
    console.error('U9统计数据计算错误:', error)
    return { total: 0, withStock: 0, zeroStock: 0 }
  }
})

/**
 * SMIS数据统计信息
 */
const smisOriginalDataStats = computed(() => {
  if (!responseSmis.value?.success || !responseSmis.value?.data) {
    return { total: 0, withStock: 0, zeroStock: 0 }
  }

  try {
    let dataArray = []
    
    // SMIS配料岛数据处理
    if (responseSmis.value.data.Data) {
      dataArray = JSON.parse(responseSmis.value.data.Data)
    } else if (Array.isArray(responseSmis.value.data)) {
      dataArray = responseSmis.value.data
    } else if (responseSmis.value.data.data && Array.isArray(responseSmis.value.data.data)) {
      dataArray = responseSmis.value.data.data
    }
    
    if (!Array.isArray(dataArray)) {
      return { total: 0, withStock: 0, zeroStock: 0 }
    }

    const total = dataArray.length
    const withStock = dataArray.filter(item => Number(item.total) > 0).length
    const zeroStock = total - withStock

    return { total, withStock, zeroStock }
  } catch (error) {
    console.error('SMIS统计数据计算错误:', error)
    return { total: 0, withStock: 0, zeroStock: 0 }
  }
})
/**
 * U9唯一物料统计
 */
const u9UniqueMaterialCount = computed(() => {
  const data = u9MaterialTableData.value
  if (!Array.isArray(data)) return 0
  
  const uniqueMaterials = new Set()
  data.forEach(item => {
    uniqueMaterials.add(`${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`)
  })
  
  return uniqueMaterials.size
})

/**
 * U9唯一批次统计
 */
const u9UniqueLotCount = computed(() => {
  const data = u9MaterialTableData.value
  if (!Array.isArray(data)) return 0
  
  const uniqueLots = new Set()
  data.forEach(item => {
    uniqueLots.add(item.LotCode)
  })
  
  return uniqueLots.size
})

/**
 * SMIS唯一物料统计
 */
const smisUniqueMaterialCount = computed(() => {
  const data = smisMaterialTableData.value
  if (!Array.isArray(data)) return 0
  
  const uniqueMaterials = new Set()
  data.forEach(item => {
    uniqueMaterials.add(`${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`)
  })
  
  return uniqueMaterials.size
})

/**
 * SMIS唯一批次统计
 */
const smisUniqueLotCount = computed(() => {
  const data = smisMaterialTableData.value
  if (!Array.isArray(data)) return 0
  
  const uniqueLots = new Set()
  data.forEach(item => {
    uniqueLots.add(item.LotCode)
  })
  
  return uniqueLots.size
})

/**
 * 表格合并方法
 */
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const key = `${rowIndex}-${columnIndex}`
  if (spanData.value[key]) {
    return spanData.value[key]
  }
  return [1, 1]
}

/**
 * U9表格合并方法
 */
const u9ArraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const key = `${rowIndex}-${columnIndex}`
  if (u9SpanData.value[key]) {
    return u9SpanData.value[key]
  }
  return [1, 1]
}

/**
 * SMIS表格合并方法
 */
const smisArraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const key = `${rowIndex}-${columnIndex}`
  if (smisSpanData.value[key]) {
    return smisSpanData.value[key]
  }
  return [1, 1]
}

/**
 * 合并表格合并方法
 */
const combinedArraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const key = `${rowIndex}-${columnIndex}`
  if (combinedSpanData.value[key]) {
    return combinedSpanData.value[key]
  }
  return [1, 1]
}

/**
 * U9表格合并计算
 */
const u9SpanData = computed(() => {
  const data = u9MaterialTableData.value
  if (!Array.isArray(data)) return {}
  
  const spanInfo = {}
  
  // 处理物料信息列的合并（ItemCode, ItemName, ItemSpec）
  for (let i = 0; i < data.length; i++) {
    const currentItem = data[i]
    
    // 检查ItemCode列
    if (i === 0 || data[i-1].ItemCode !== currentItem.ItemCode || 
        data[i-1].ItemName !== currentItem.ItemName || 
        data[i-1].ItemSpec !== currentItem.ItemSpec) {
      
      // 计算相同物料的行数
      let sameItemCount = 1
      for (let j = i + 1; j < data.length; j++) {
        if (data[j].ItemCode === currentItem.ItemCode && 
            data[j].ItemName === currentItem.ItemName && 
            data[j].ItemSpec === currentItem.ItemSpec) {
          sameItemCount++
        } else {
          break
        }
      }
      
      // 设置物料信息列的合并
      spanInfo[`${i}-0`] = [sameItemCount, 1] // ItemCode
      spanInfo[`${i}-1`] = [sameItemCount, 1] // ItemName
      spanInfo[`${i}-2`] = [sameItemCount, 1] // ItemSpec
      
      // 后续相同物料的行设置为不显示
      for (let k = 1; k < sameItemCount; k++) {
        spanInfo[`${i+k}-0`] = [0, 0] // ItemCode
        spanInfo[`${i+k}-1`] = [0, 0] // ItemName
        spanInfo[`${i+k}-2`] = [0, 0] // ItemSpec
      }
    }
  }
  
  return spanInfo
})

/**
 * SMIS表格合并计算
 */
const smisSpanData = computed(() => {
  const data = smisMaterialTableData.value
  if (!Array.isArray(data)) return {}
  
  const spanInfo = {}
  
  // 处理物料信息列的合并（ItemCode, ItemName, ItemSpec）
  for (let i = 0; i < data.length; i++) {
    const currentItem = data[i]
    
    // 检查ItemCode列
    if (i === 0 || data[i-1].ItemCode !== currentItem.ItemCode || 
        data[i-1].ItemName !== currentItem.ItemName || 
        data[i-1].ItemSpec !== currentItem.ItemSpec) {
      
      // 计算相同物料的行数
      let sameItemCount = 1
      for (let j = i + 1; j < data.length; j++) {
        if (data[j].ItemCode === currentItem.ItemCode && 
            data[j].ItemName === currentItem.ItemName && 
            data[j].ItemSpec === currentItem.ItemSpec) {
          sameItemCount++
        } else {
          break
        }
      }
      
      // 设置物料信息列的合并
      spanInfo[`${i}-0`] = [sameItemCount, 1] // ItemCode
      spanInfo[`${i}-1`] = [sameItemCount, 1] // ItemName
      spanInfo[`${i}-2`] = [sameItemCount, 1] // ItemSpec
      
      // 后续相同物料的行设置为不显示
      for (let k = 1; k < sameItemCount; k++) {
        spanInfo[`${i+k}-0`] = [0, 0] // ItemCode
        spanInfo[`${i+k}-1`] = [0, 0] // ItemName
        spanInfo[`${i+k}-2`] = [0, 0] // ItemSpec
      }
    }
  }
  
  return spanInfo
})

/**
 * 合并的库存表格数据计算属性
 * 将U9和SMIS的数据合并在一起显示，相同物料放在一起
 */
const combinedMaterialTableData = computed(() => {
  const u9Data = u9MaterialTableData.value || []
  const smisData = smisMaterialTableData.value || []
  
  if (u9Data.length === 0 && smisData.length === 0) {
    return []
  }
  
  // 创建物料信息映射
  const materialMap = new Map()
  
  // 处理U9数据
  u9Data.forEach(item => {
    const materialKey = `${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`
    if (!materialMap.has(materialKey)) {
      materialMap.set(materialKey, {
        ItemCode: item.ItemCode,
        ItemName: item.ItemName,
        ItemSpec: item.ItemSpec,
        u9Records: [],
        smisRecords: []
      })
    }
    materialMap.get(materialKey).u9Records.push(item)
  })
  
  // 处理SMIS数据
  smisData.forEach(item => {
    const materialKey = `${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`
    if (!materialMap.has(materialKey)) {
      materialMap.set(materialKey, {
        ItemCode: item.ItemCode,
        ItemName: item.ItemName,
        ItemSpec: item.ItemSpec,
        u9Records: [],
        smisRecords: []
      })
    }
    materialMap.get(materialKey).smisRecords.push(item)
  })
  
  // 生成合并后的表格数据
  const combinedData = []
  
  // 按物料编码排序
  const sortedMaterials = Array.from(materialMap.values()).sort((a, b) => 
    a.ItemCode.localeCompare(b.ItemCode)
  )
  
  sortedMaterials.forEach(material => {
    const { ItemCode, ItemName, ItemSpec, u9Records, smisRecords } = material
    
    // 合并同一物料的所有记录
    const allRecords = []
    
    // 添加U9记录
    u9Records.forEach(record => {
      allRecords.push({
        ...record,
        systemType: 'U9',
        systemTag: 'U9仓库',
        systemColor: 'primary'
      })
    })
    
    // 添加SMIS记录
    smisRecords.forEach(record => {
      allRecords.push({
        ...record,
        systemType: 'SMIS',
        systemTag: '配料岛',
        systemColor: 'success'
      })
    })
    
    // 按系统类型、批次号、仓库排序
    allRecords.sort((a, b) => {
      // 先按批次号排序
      if (a.LotCode !== b.LotCode) {
        return a.LotCode.localeCompare(b.LotCode)
      }
      // 相同批次下按系统类型排序（U9在前）
      if (a.systemType !== b.systemType) {
        return a.systemType === 'U9' ? -1 : 1
      }
      // 最后按仓库名称排序
      return a.WhName.localeCompare(b.WhName)
    })
    
    combinedData.push(...allRecords)
  })
  
  return combinedData
})

/**
 * 合并表格的合并计算
 */
const combinedSpanData = computed(() => {
  const data = combinedMaterialTableData.value
  if (!Array.isArray(data) || data.length === 0) return {}
  
  const spanInfo = {}
  
  // 处理物料信息列的合并（ItemCode, ItemName, ItemSpec）
  for (let i = 0; i < data.length; i++) {
    const currentItem = data[i]
    
    // 检查物料信息是否相同
    if (i === 0 || 
        data[i-1].ItemCode !== currentItem.ItemCode || 
        data[i-1].ItemName !== currentItem.ItemName || 
        data[i-1].ItemSpec !== currentItem.ItemSpec) {
      
      // 计算相同物料的行数
      let sameItemCount = 1
      for (let j = i + 1; j < data.length; j++) {
        if (data[j].ItemCode === currentItem.ItemCode && 
            data[j].ItemName === currentItem.ItemName && 
            data[j].ItemSpec === currentItem.ItemSpec) {
          sameItemCount++
        } else {
          break
        }
      }
      
      // 设置物料信息列的合并
      spanInfo[`${i}-0`] = [sameItemCount, 1] // ItemCode
      spanInfo[`${i}-1`] = [sameItemCount, 1] // ItemName
      spanInfo[`${i}-2`] = [sameItemCount, 1] // ItemSpec
      
      // 后续相同物料的行设置为不显示
      for (let k = 1; k < sameItemCount; k++) {
        spanInfo[`${i+k}-0`] = [0, 0] // ItemCode
        spanInfo[`${i+k}-1`] = [0, 0] // ItemName
        spanInfo[`${i+k}-2`] = [0, 0] // ItemSpec
      }
    }
  }
  
  // 处理批次号合并
  for (let i = 0; i < data.length; i++) {
    const currentItem = data[i]
    
    // 检查批次号是否相同（在同一物料下）
    if (i === 0 || 
        data[i-1].ItemCode !== currentItem.ItemCode || 
        data[i-1].ItemName !== currentItem.ItemName || 
        data[i-1].ItemSpec !== currentItem.ItemSpec ||
        data[i-1].LotCode !== currentItem.LotCode) {
      
      // 计算相同批次的行数（在同一物料下）
      let sameLotCount = 1
      for (let j = i + 1; j < data.length; j++) {
        if (data[j].ItemCode === currentItem.ItemCode && 
            data[j].ItemName === currentItem.ItemName && 
            data[j].ItemSpec === currentItem.ItemSpec &&
            data[j].LotCode === currentItem.LotCode) {
          sameLotCount++
        } else {
          break
        }
      }
      
      // 设置批次号合并
      spanInfo[`${i}-3`] = [sameLotCount, 1] // LotCode
      
      // 后续相同批次的行设置为不显示
      for (let k = 1; k < sameLotCount; k++) {
        spanInfo[`${i+k}-3`] = [0, 0] // LotCode
      }
    }
  }
  
  return spanInfo
})

/**
 * 合并表格统计信息
 */
const combinedTableStats = computed(() => {
  const data = combinedMaterialTableData.value
  if (!Array.isArray(data) || data.length === 0) {
    return {
      totalRecords: 0,
      uniqueMaterials: 0,
      uniqueLots: 0,
      u9Records: 0,
      smisRecords: 0,
      hasStock: 0,
      zeroStock: 0
    }
  }
  
  const uniqueMaterials = new Set()
  const uniqueLots = new Set()
  let u9Records = 0
  let smisRecords = 0
  let hasStock = 0
  let zeroStock = 0
  
  data.forEach(item => {
    // 统计唯一物料
    uniqueMaterials.add(`${item.ItemCode}-${item.ItemName}-${item.ItemSpec}`)
    
    // 统计唯一批次
    uniqueLots.add(item.LotCode)
    
    // 统计系统记录数
    if (item.systemType === 'U9') {
      u9Records++
    } else if (item.systemType === 'SMIS') {
      smisRecords++
    }
    
    // 统计库存情况
    if (item.StoreQty > 0) {
      hasStock++
    } else {
      zeroStock++
    }
  })
  
  return {
    totalRecords: data.length,
    uniqueMaterials: uniqueMaterials.size,
    uniqueLots: uniqueLots.size,
    u9Records,
    smisRecords,
    hasStock,
    zeroStock
  }
})

/**
 * 发送物料库存查询请求（支持多个物料编码）
 */
const sendRequestStock = async () => {
  // 参数验证
  if (!businessParams.itemCode.trim()) {
    ElMessage.warning('请输入物料编码')
    return
  }
  
  loadingStock.value = true
  responseStock.value = null
  const startTime = Date.now()
  
  try {
    // 处理多个物料编码（用逗号分隔）
    const itemCodes = businessParams.itemCode.split(',').map(code => code.trim()).filter(code => code)
    
    if (itemCodes.length === 0) {
      ElMessage.warning('请输入有效的物料编码')
      return
    }
    
    console.log(`开始查询 ${itemCodes.length} 个物料编码:`, itemCodes)
    
    // 并行查询所有物料编码
    const promises = itemCodes.map(async (itemCode) => {
      const requestBody = {
        context: {
          CultureName: 'zh-CN',
          EntCode: '01',
          OrgCode: '1001',
          UserCode: 'DINGDING'
        },
        itemCode: itemCode,
        lotCode: businessParams.lotCode || ''
      }
      
      return DataService.postData('/api/u9/stock', requestBody)
    })
    
    const results = await Promise.allSettled(promises)
    
    // 合并所有成功的查询结果
    const allData = []
    let successCount = 0
    let failCount = 0
    
    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value.success) {
        const dataArray = parseResponseData(result.value.data)
        allData.push(...dataArray)
        successCount++
        console.log(`物料编码 ${itemCodes[index]} 查询成功，找到 ${dataArray.length} 条记录`)
      } else {
        failCount++
        console.warn(`物料编码 ${itemCodes[index]} 查询失败:`, result.reason || result.value?.error)
      }
    })
    
    responseTimeStock.value = Date.now() - startTime
    
    // 构造合并后的响应数据
    responseStock.value = {
      success: allData.length > 0,
      data: {
        Data: JSON.stringify(allData)
      },
      error: allData.length === 0 ? '所有物料编码查询失败' : null
    }

    if (allData.length > 0) {
      // 生成数据的唯一标识
      const dataKey = `U9_Stock_${businessParams.itemCode || 'Query'}_${Date.now()}`
      
      // 处理并存储表格数据到dataStore
      const tableData = u9MaterialTableData.value
      
      dataStore.addData(dataKey, {
        original: { Data: JSON.stringify(allData) },
        tableData: tableData,
        summary: {
          totalRecords: tableData.length,
          hasStock: tableData.filter(item => item.StoreQty > 0).length,
          noStock: tableData.filter(item => item.StoreQty === 0).length
        }
      }, {
        name: `物料库存数据-${businessParams.itemCode || '物料'}`,
        url: '/api/u9/stock',
        method: 'POST',
        params: { itemCodes: itemCodes, lotCode: businessParams.lotCode },
        type: 'U9_STOCK'
      })
      
      const queryDescription = businessParams.lotCode.trim() 
        ? `${itemCodes.length}个物料的批次 ${businessParams.lotCode}` 
        : `${itemCodes.length}个物料的所有批次`
      
      ElMessage.success(`查询完成！成功 ${successCount} 个，失败 ${failCount} 个，共找到 ${allData.length} 条${queryDescription}的库存记录`)
    } else {
      const errorKey = `U9_Stock_Error_${Date.now()}`
      dataStore.addError(errorKey, '所有物料编码查询失败')
      ElMessage.error(`查询失败：${successCount} 个成功，${failCount} 个失败`)
    }
  } catch (error) {
    responseTimeStock.value = Date.now() - startTime
    responseStock.value = {
      success: false,
      error: error.message || '网络请求失败'
    }
    
    const errorKey = `U9_Stock_Error_${Date.now()}`
    dataStore.addError(errorKey, error.message || '网络请求失败')
    ElMessage.error('请求异常')
  } finally {
    loadingStock.value = false
  }
}

/**
 * 发送SMIS配料岛库存查询请求
 */
const sendRequestSmis = async () => {
  // 参数验证
  if (!businessParams.itemCode.trim()) {
    ElMessage.warning('请输入物料编码')
    return
  }
  
  loadingSmis.value = true
  responseSmis.value = null
  const startTime = Date.now()
  
  try {
    // 处理多个物料编码（用逗号分隔）
    const itemCodes = businessParams.itemCode.split(',').map(code => code.trim()).filter(code => code)
    
    if (itemCodes.length === 0) {
      ElMessage.warning('请输入有效的物料编码')
      return
    }
    
    console.log(`开始查询SMIS ${itemCodes.length} 个物料编码:`, itemCodes)
    
    // 构建请求参数 - 传递完整的物料编码字符串（后端支持逗号分隔）
    const requestParams = {
      itemCode: itemCodes.join(','), // 重新组合物料编码，确保没有多余空格
      lotCode: businessParams.lotCode || ''
    }
    
    const result = await DataService.fetchSmisStock(requestParams)
    
    responseTimeSmis.value = Date.now() - startTime
    responseSmis.value = result

    if (result.success) {
      // 生成数据的唯一标识
      const dataKey = `SMIS_Stock_${businessParams.itemCode || 'Query'}_${Date.now()}`
      
      // 处理并存储表格数据到dataStore
      const tableData = smisMaterialTableData.value
      
      dataStore.addData(dataKey, {
        original: result.data,
        tableData: tableData,
        summary: {
          totalRecords: tableData.length,
          hasStock: tableData.filter(item => item.StoreQty > 0).length,
          noStock: tableData.filter(item => item.StoreQty === 0).length
        }
      }, {
        name: `配料岛库存数据-${businessParams.itemCode || '物料'}`,
        url: '/api/smis/materialstock',
        method: 'GET',
        params: requestParams,
        type: 'SMIS_STOCK'
      })
      
      const queryDescription = businessParams.lotCode.trim() 
        ? `${itemCodes.length}个物料的批次 ${businessParams.lotCode}` 
        : `${itemCodes.length}个物料的所有批次`
      
      ElMessage.success(`查询成功！共找到 ${tableData.length} 条${queryDescription}的配料岛库存记录`)
    } else {
      const errorKey = `SMIS_Stock_Error_${Date.now()}`
      dataStore.addError(errorKey, result.error)
      ElMessage.error(`查询失败: ${result.error}`)
    }
  } catch (error) {
    responseTimeSmis.value = Date.now() - startTime
    responseSmis.value = {
      success: false,
      error: error.message || '网络请求失败'
    }
    
    const errorKey = `SMIS_Stock_Error_${Date.now()}`
    dataStore.addError(errorKey, error.message || '网络请求失败')
    ElMessage.error('请求异常')
  } finally {
    loadingSmis.value = false
  }
}

/**
 * 统一查询所有系统（U9和SMIS）
 */
const queryAllSystems = async () => {
  // 参数验证
  if (!businessParams.itemCode.trim()) {
    ElMessage.warning('请输入物料编码')
    return
  }

  ElMessage.info('开始查询库存信息，请稍候...')
  
  // 并行查询U9和SMIS系统
  const promises = [
    sendRequestStock(),
    sendRequestSmis()
  ]

  try {
    await Promise.allSettled(promises)
    
    // 检查查询结果
    const u9Success = responseStock.value?.success
    const smisSuccess = responseSmis.value?.success
    
    let message = '查询完成！'
    if (u9Success && smisSuccess) {
      message = `查询成功！U9系统：${u9MaterialTableData.value.length}条记录，配料岛系统：${smisMaterialTableData.value.length}条记录`
    } else if (u9Success) {
      message = `查询完成！U9系统：${u9MaterialTableData.value.length}条记录，配料岛系统查询失败`
    } else if (smisSuccess) {
      message = `查询完成！配料岛系统：${smisMaterialTableData.value.length}条记录，U9系统查询失败`
    } else {
      message = '查询失败！两个系统都无法获取数据'
    }
    
    if (u9Success || smisSuccess) {
      ElMessage.success(message)
    } else {
      ElMessage.error(message)
    }
  } catch (error) {
    console.error('统一查询异常:', error)
    ElMessage.error('查询过程中发生异常')
  }
}

/**
 * 处理Excel文件导入
 */
const handleExcelImport = async (file) => {
  try {
    batchLoading.value = true
    
    const fileReader = new FileReader()
    fileReader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        
        if (jsonData.length === 0) {
          ElMessage.warning('Excel文件为空，请检查文件内容')
          return
        }
        
        // 验证Excel格式
        const firstRow = jsonData[0]
        if (!firstRow['物料编码'] && !firstRow['itemCode']) {
          ElMessage.error('Excel格式错误，请确保包含"物料编码"列')
          return
        }
        
        // 处理导入的数据
        const importItems = jsonData.map((row, index) => ({
          rowIndex: index + 2, // Excel行号（从第2行开始，第1行是标题）
          itemCode: String(row['物料编码'] || row['itemCode'] || '').trim(), // 转换为字符串并去除前后空格
          lotCode: String(row['批次编码'] || row['lotCode'] || '').trim() // 转换为字符串并去除前后空格
        })).filter(item => item.itemCode) // 过滤掉没有物料编码的行
        
        if (importItems.length === 0) {
          ElMessage.warning('没有找到有效的物料编码数据')
          return
        }
        
        ElMessage.info(`准备查询 ${importItems.length} 个物料的库存信息`)
        
        // 批量查询
        await batchQueryStock(importItems)
        
      } catch (error) {
        ElMessage.error(`解析Excel文件失败: ${error.message}`)
      } finally {
        batchLoading.value = false
      }
    }
    
    fileReader.readAsArrayBuffer(file.raw)
  } catch (error) {
    ElMessage.error(`导入失败: ${error.message}`)
    batchLoading.value = false
  }
}

/**
 * 批量查询库存（同时查询U9和SMIS）
 */
const batchQueryStock = async (importItems) => {
  const u9Results = []
  const smisResults = []
  let u9SuccessCount = 0
  let u9FailCount = 0
  let smisSuccessCount = 0
  let smisFailCount = 0
  
  for (let i = 0; i < importItems.length; i++) {
    const item = importItems[i]
    
    try {
      // 查询U9系统
      const u9RequestBody = {
        context: {
          CultureName: 'zh-CN',
          EntCode: '01',
          OrgCode: '1001',
          UserCode: 'DINGDING'
        },
        itemCode: item.itemCode.trim(), // 确保去除空格
        lotCode: item.lotCode.trim() // 确保去除空格
      }
      
      const u9Result = await DataService.postData('/api/u9/stock', u9RequestBody)
      
      if (u9Result.success) {
        const u9DataArray = parseResponseData(u9Result.data)
        u9Results.push(...u9DataArray.map(data => ({
          ...data,
          _sourceRow: item.rowIndex,
          _sourceItemCode: item.itemCode,
          _sourceLotCode: item.lotCode
        })))
        u9SuccessCount++
      } else {
        u9FailCount++
        console.warn(`第${item.rowIndex}行U9查询失败: ${u9Result.error}`)
      }
      
      // 查询SMIS系统
      const smisRequestParams = {
        itemCode: item.itemCode.trim(), // 确保去除空格
        lotCode: item.lotCode.trim() // 确保去除空格
      }
      
      const smisResult = await DataService.fetchSmisStock(smisRequestParams)
      
      if (smisResult.success) {
        let smisDataArray = []
        if (smisResult.data.Data) {
          smisDataArray = JSON.parse(smisResult.data.Data)
        } else if (Array.isArray(smisResult.data)) {
          smisDataArray = smisResult.data
        } else if (smisResult.data.data && Array.isArray(smisResult.data.data)) {
          smisDataArray = smisResult.data.data
        }
        
        // 保持原始格式以适配计算属性
        const smisStandardData = smisDataArray.map(smisItem => ({
          materialcode: smisItem.materialcode || '-',
          materialname: smisItem.materialname || '-',
          materialgg: smisItem.materialgg || '-',
          venderlot: smisItem.venderlot || '-',
          warehousename: smisItem.warehousename || '-',
          total: Number(smisItem.total) || 0,
          usestock: Number(smisItem.usestock) || 0,
          warehousecode: smisItem.warehousecode || '-',
          _sourceRow: item.rowIndex,
          _sourceItemCode: item.itemCode,
          _sourceLotCode: item.lotCode
        }))
        
        smisResults.push(...smisStandardData)
        smisSuccessCount++
      } else {
        smisFailCount++
        console.warn(`第${item.rowIndex}行SMIS查询失败: ${smisResult.error}`)
      }
      
      // 添加延迟避免请求过于频繁
      if (i < importItems.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 300))
      }
      
    } catch (error) {
      u9FailCount++
      smisFailCount++
      ElMessage.error(`第${item.rowIndex}行查询异常: ${error.message}`)
    }
  }
  
  // 更新U9结果
  if (u9Results.length > 0) {
    batchResults.value = u9Results
    
    responseStock.value = {
      success: true,
      data: {
        Data: JSON.stringify(u9Results)
      }
    }
  } else if (u9SuccessCount > 0) {
    // 如果有成功的查询但没有数据，也要更新响应状态
    responseStock.value = {
      success: true,
      data: {
        Data: JSON.stringify([])
      }
    }
    batchResults.value = []
  }
  
  // 更新SMIS结果
  if (smisResults.length > 0) {
    responseSmis.value = {
      success: true,
      data: {
        Data: JSON.stringify(smisResults)
      }
    }
  } else if (smisSuccessCount > 0) {
    // 如果有成功的查询但没有数据，也要更新响应状态
    responseSmis.value = {
      success: true,
      data: {
        Data: JSON.stringify([])
      }
    }
  }
  
  // 显示结果统计
  const totalQueries = importItems.length
  const u9Message = `U9系统：成功 ${u9SuccessCount}，失败 ${u9FailCount}`
  const smisMessage = `配料岛系统：成功 ${smisSuccessCount}，失败 ${smisFailCount}`
  
  if (u9Results.length > 0 || smisResults.length > 0) {
    ElMessage.success(`批量查询完成！共查询 ${totalQueries} 个物料\n${u9Message}\n${smisMessage}`)
  } else {
    ElMessage.warning(`批量查询完成，但未获取到任何数据\n${u9Message}\n${smisMessage}`)
  }
}

/**
 * 下载导入模板
 */
const downloadTemplate = () => {
  const templateData = [
    { '物料编码': 'PT0302-220674', '批次编码': '' },
    { '物料编码': '10.02.002.00203', '批次编码': 'LOT001' },
    { '物料编码': '', '批次编码': '' }
  ]
  
  const worksheet = XLSX.utils.json_to_sheet(templateData)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '物料库存查询模板')
  
  // 设置列宽
  worksheet['!cols'] = [
    { wch: 20 }, // 物料编码列宽
    { wch: 15 }  // 批次编码列宽
  ]
  
  XLSX.writeFile(workbook, '物料库存查询模板.xlsx')
  ElMessage.success('模板下载成功')
}

/**
 * 导出合并结果到Excel（U9和SMIS数据合并在同一个工作表中）
 */
const exportCombinedToExcel = () => {
  const hasU9Data = responseStock.value?.success && u9MaterialTableData.value.length > 0
  const hasSmisData = responseSmis.value?.success && smisMaterialTableData.value.length > 0
  
  if (!hasU9Data && !hasSmisData) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  try {
    // 合并U9和SMIS数据到同一个工作表
    const combinedData = []
    
    // 添加U9数据
    if (hasU9Data) {
      u9MaterialTableData.value.forEach(item => {
        combinedData.push({
          '物料编码': item.ItemCode,
          '物料名称': item.ItemName,
          '型号': item.ItemSpec,
          '批次号': item.LotCode,
          '仓库名称': item.WhName,
          '库存量': item.StoreQty,
          '借出量': item.LendQty,
          '组织名称': item.OrgName,
          '数据源': 'U9仓库'
        })
      })
    }
    
    // 添加SMIS数据
    if (hasSmisData) {
      smisMaterialTableData.value.forEach(item => {
        combinedData.push({
          '物料编码': item.ItemCode,
          '物料名称': item.ItemName,
          '型号': item.ItemSpec,
          '批次号': item.LotCode,
          '仓库名称': item.WhName,
          '库存量': item.StoreQty,
          '借出量': item.LendQty,
          '组织名称': item.OrgName,
          '数据源': '配料岛'
        })
      })
    }
    
    // 按物料编码、数据源排序（同一物料的不同系统数据相邻显示）
    combinedData.sort((a, b) => {
      const itemCodeCompare = a['物料编码'].localeCompare(b['物料编码'])
      if (itemCodeCompare !== 0) {
        return itemCodeCompare
      }
      // 相同物料时，U9仓库排在前面
      return a['数据源'].localeCompare(b['数据源'])
    })
    
    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(combinedData)
    const workbook = XLSX.utils.book_new()
    
    // 设置列宽
    worksheet['!cols'] = [
      { wch: 18 }, // 物料编码
      { wch: 20 }, // 物料名称
      { wch: 25 }, // 型号
      { wch: 20 }, // 批次号
      { wch: 15 }, // 仓库名称
      { wch: 10 }, // 库存量
      { wch: 10 }, // 借出量
      { wch: 20 }, // 组织名称
      { wch: 12 }  // 数据源
    ]
    
    XLSX.utils.book_append_sheet(workbook, worksheet, '库存数据')
    
    // 生成文件名
    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
    const systemInfo = []
    if (hasU9Data) systemInfo.push(`U9(${u9MaterialTableData.value.length}条)`)
    if (hasSmisData) systemInfo.push(`配料岛(${smisMaterialTableData.value.length}条)`)
    
    const filename = `库存数据_${systemInfo.join('_')}_${businessParams.itemCode || '查询'}_${timestamp}.xlsx`
    
    XLSX.writeFile(workbook, filename)
    
    ElMessage.success(`数据导出成功！包含${systemInfo.join('、')}，文件名：${filename}`)
  } catch (error) {
    console.error('数据导出失败:', error)
    ElMessage.error('数据导出失败')
  }
}
</script>

<style scoped>
.u9-api-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  margin-left: 8px;
}

.business-config {
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 24px;
}

.action-section {
  margin-bottom: 24px;
}

.help-text {
  margin-top: 8px;
  text-align: center;
}

.response-section {
  margin-bottom: 24px;
}

.table-summary {
  margin-bottom: 16px;
}

.material-info-cell {
  min-width: 120px;
}

.lot-code-cell {
  min-width: 100px;
}

.el-card {
  border: none;
  border-radius: 8px;
  overflow: hidden;
}

.el-tabs__header {
  background-color: #f3f3f3;
  border-bottom: 1px solid #eaeaea;
}

.el-tab-pane {
  padding: 16px;
  background-color: #fff;
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
}

.el-table th {
  background-color: #f3f3f3;
  font-weight: 500;
}

.el-table td {
  vertical-align: middle;
}

.el-empty {
  margin-top: 32px;
}

/* 合并表格样式 */
.combined-table .material-info-cell {
  background-color: #f8f9fa;
  font-weight: 500;
}

.combined-table .system-tag-cell {
  text-align: center;
}

.combined-table .el-table__row:hover {
  background-color: #f5f7fa;
}

/* 表格行样式区分 */
.combined-table .el-table__row[data-system="U9"] {
  background-color: #f0f9ff;
}

.combined-table .el-table__row[data-system="SMIS"] {
  background-color: #f0fff4;
}

.table-summary .el-text {
  font-size: 14px;
  font-weight: 500;
}
</style>